package com.xk._02算法篇._05backTracking.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.cn/problems/n-queens/
 * @description: 51 N皇后问题 优化
 * @author: xu
 * @date: 2022/10/18 14:30
 */
public class Test01_er {
    public static void main(String[] args) {
        List<List<String>> lists = new Test01_er().solveNQueens(4);
        System.out.println(lists);
    }

    private int[] queens; // 索引下标为行号，元素值为列号
    private boolean[] cols;
    private boolean[] ltTop;
    private boolean[] rtTop;

    public List<List<String>> solveNQueens(int n) {
        if (n < 1) return null;
        List<List<String>> res = new ArrayList<>();
        queens = new int[n]; // 索引下标为行号，元素值为列号
        cols = new boolean[n];
        ltTop = new boolean[(n<<1) - 1];
        rtTop = new boolean[ltTop.length];
        plate(0, res);
        return res;
    }

    private void plate(int row, List<List<String>> res){
        if (row == queens.length) {
            put(res, queens);
            return;
        }

        for (int col = 0; col < queens.length; col++) {
            // 剪枝
            if (cols[col]) continue;
            int ltIdx = row - col + queens.length - 1;
            int rtIdx = row + col;
            if (ltTop[ltIdx] || rtTop[rtIdx]) continue;

            cols[col] = ltTop[ltIdx] = rtTop[rtIdx] = true;
            queens[row] = col;
            plate(row+1, res);

            cols[col] = ltTop[ltIdx] = rtTop[rtIdx] = false;
        }
    }

    private void put(List<List<String>> res, int[] queens) {
        List<String> list = new ArrayList<>();
        for (int r = 0; r < queens.length; r++){
            StringBuilder sb = new StringBuilder();
            for (int c = 0; c < queens.length; c++){
                if (queens[r] == c) sb.append("Q");
                else sb.append(".");
            }
            list.add(sb.toString());
        }
        res.add(list);
    }
}
